use chrono::{DateTime, Utc};
use deadpool_postgres::{Config, Runtime::Tokio1};
use geo_types::Point;
use postgres_types::{FromSql, ToSql};
use tokio_postgres::NoTls;
use uuid::{self, Uuid};
pub mod settings;
use crate::settings::Settings;
//参考blog  https://www.cnblogs.com/pythonClub/p/17804728.html

#[derive(Debug, ToSql, FromSql)]
pub struct City {
    pub name: String,
    pub location: Point<f64>,
}
#[derive(Debug, ToSql, FromSql)]
pub struct User {
    pub user_id: Uuid,
    pub username: String,
    pub email: String,
    pub pwd_hash: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: Option<DateTime<Utc>>,
}
#[tokio::main]
async fn main() {
    env_logger::init();
    // settings::get_database();
    let setting = Settings::get();
    println!("{:?}", setting);
    //获取连接
    let client = get_client().await.unwrap();

    //执行sql查询
    let rows = match client.query("select * from cities", &[]).await {
        Ok(res) => res,
        Err(e) => panic!("查询出错{}", e),
    };
    //遍历结果，并映射到表格,以行列形式
    for row in rows {
        let name: String = row.get(0);
        let point: Point<f64> = row.get(1);
        println!("{:?}", row);
        let city_s = City {
            name: name,
            location: Point::new(point.x(), point.y()),
        };

        println!("city:{:?}", city_s);
    }
    let rows2 = match client.query("select * from users", &[]).await {
        Ok(rows) => rows,
        Err(e) => panic!("查询出错{}", e),
    };
    //遍历结果，并映射到表格,以行列形式
    for row in rows2 {
        let user_id: Uuid = row.get(0);
        let username: String = row.get(1);
        let email: String = row.get(2);
        let pwd_hash = row.get(3);
        let created = row.get(4);
        let updated = row.get(5);
        println!("{:?}", row);
        let user = User {
            user_id,
            username,
            email,
            pwd_hash,
            created_at: created,
            updated_at: updated,
        };

        println!("user:{:?}", user);
    }
}
fn get_cfg() -> deadpool_postgres::Config {
    //配置数据库
    let mut cfg = Config::new();
    cfg.user = Some("postgres".to_string());
    cfg.password = Some("gkdb1234!@#$".to_string());
    cfg.dbname = Some("devdb".to_string());
    cfg.host = Some("192.168.114.156".to_string());
    cfg.port = Some(5432);
    cfg
}
async fn get_client() -> Result<deadpool_postgres::Client, String> {
    //创建连接池
    let pool = get_cfg()
        .create_pool(Some(Tokio1), NoTls)
        .map_err(|err| err.to_string())?;
    pool.get().await.map_err(|err| err.to_string())
}
